// 
//  dispfix.c
//  
//  Author:
//       Nikita Tsukanov <keks9n@gmail.com>
// 
//  Copyright (c) 2011 Nikita Tsukanov
// 
//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation; either version 2 of the License, or
//  (at your option) any later version.
// 
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//  GNU General Public License for more details.
//  
//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// 

#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

void* (*next_xod) (char* name)=NULL;


void*XOpenDisplay(char*name)
{
	if(next_xod==0)
	{
		next_xod=dlsym(RTLD_NEXT, "XOpenDisplay");
		if(next_xod==0)
		{
			fprintf(stderr, "Unable to get XOpenDisplay address\n");
			exit(1);
		}
	}

	//Only if opening default display
	if(name==NULL)
	{

		char *envdisp=strdup(getenv("ST_DISPLAY"));

		if(envdisp != NULL)
		{
			char *envexe=getenv("ST_EXE");
			if(envexe != NULL)
			{
				char comm[256];
				sprintf(comm, "/proc/%i/comm", getpid());
				FILE *commfile=fopen(comm, "r");
				if(commfile == NULL)
				{
					fprintf(stderr, "Cann't read executable file name. Is /proc mounted?\n");
					exit(1);
				}
				fgets(comm, 256, commfile);
				fclose(commfile);
				
				int c=0;
				while(comm[c]!=0)
				{
					if(comm[c]=='\n')
					{
						comm[c]=0;
						break;
					}
					c++;
				}


				if(strcmp(comm, envexe)==0)
				{
					name=strdup(envdisp);
				}
			}
			free(envdisp);
		}
	}
	return next_xod(name);

}
